<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Telegram风格聊天界面</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            display: flex;
            height: 100vh;
            background-color: #f0f0f0;
        }

        /* 左侧对话列表样式 */
        .dialogs {
            width: 350px;
            background-color: #fff;
            border-right: 1px solid #e0e0e0;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .search-container {
            padding: 15px;
            background-color: #f5f5f5;
            border-bottom: 1px solid #e0e0e0;
            position: relative;
        }

        .search-bar {
            display: flex;
            align-items: center;
            background-color: #e9e9e9;
            border-radius: 20px;
            padding: 5px 15px;
        }

        .search-bar i {
            color: #888;
            margin-right: 8px;
        }

        .search-bar input {
            width: 100%;
            padding: 8px 0;
            border: none;
            background: transparent;
            font-size: 14px;
            outline: none;
        }

        .dialogs-list {
            overflow-y: auto;
            flex: 1;
        }

        .dialog-item {
            display: flex;
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .dialog-item.active {
            background-color: #f0f7ff;
        }

        .dialog-item:hover {
            background-color: #f5f5f5;
        }

        .dialog-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: #3a9fea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .dialog-info {
            flex: 1;
            min-width: 0;
        }

        .dialog-name {
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }

        .dialog-last-message {
            color: #707070;
            font-size: 14px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .dialog-time {
            color: #a0a0a0;
            font-size: 12px;
            flex-shrink: 0;
        }

        /* 右侧聊天窗口样式 */
        .chat {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #e6ebf0;
        }

        .chat-header {
            padding: 15px;
            background-color: #fff;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
        }

        .chat-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #3a9fea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            font-weight: bold;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .chat-name {
            font-weight: bold;
            flex: 1;
        }

        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
            max-width: 80%;
        }

        .message-content {
            padding: 10px 15px;
            border-radius: 10px;
            position: relative;
            word-break: break-word;
        }

        .message-time-outgoing {
            font-size: 11px;
            color: #a0a0a0;
            margin-top: 5px;
            align-self: flex-end;
        }

        .message-time-incoming {
            font-size: 11px;
            color: #a0a0a0;
            margin-top: 5px;
            align-self: flex-start;
        }

        .message-incoming {
            align-items: flex-start;
        }

        .message-incoming .message-content {
            background-color: #fff;
            border-top-left-radius: 0;
        }

        .message-outgoing {
            align-items: flex-end;
            align-self: flex-end;
        }

        .message-outgoing .message-content {
            background-color: rgba(82, 171, 239, 0.823);
            border-top-right-radius: 0;
        }

        .chat-input {
            padding: 15px;
            background-color: #fff;
            border-top: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
        }

        .chat-input input {
            flex: 1;
            padding: 12px 15px;
            border: none;
            border-radius: 20px;
            background-color: #f5f5f5;
            font-size: 14px;
            outline: none;
        }

        .send-button {
            margin-left: 10px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #3a9fea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: none;
            outline: none;
        }

        .no-chat-selected {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #888;
        }

        .no-chat-selected i {
            font-size: 48px;
            margin-bottom: 20px;
        }

        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            max-height: 300px;
            overflow-y: auto;
            z-index: 100;
            display: none;
        }

        .search-result-item {
            padding: 12px 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #f0f0f0;
        }

        .search-result-item:hover {
            background-color: #f5f5f5;
        }

        .search-result-item i {
            margin-right: 10px;
            color: #3a9fea;
        }

        .empty-state {
            padding: 20px;
            text-align: center;
            color: #888;
        }

        /* 未读消息数样式 */
        .unread-count {
            background-color: #3a9fea;
            color: white;
            border-radius: 12px;
            min-width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            margin-left: 8px;
            padding: 0 6px;
        }
    </style>
</head>

<body>
    <!-- 左侧对话列表 -->
    <div class="dialogs">
        <div class="search-container">
            <div class="search-bar">
                <i class="fas fa-search"></i>
                <input type="text" id="search-input" placeholder="搜索对话或消息">
            </div>
            <div class="search-results" id="search-results">
                <!-- 搜索结果将在这里显示 -->
            </div>
        </div>

        <div class="dialogs-list" id="dialogs-list">
            <!-- 对话列表将通过JS生成 -->
        </div>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat">
        <div class="chat-header" id="chat-header">
            <div class="chat-avatar" id="current-chat-avatar">T</div>
            <div class="chat-name" id="current-chat-name">Telegram</div>
        </div>

        <div class="chat-messages" id="chat-messages">
            <div class="no-chat-selected" id="no-chat-selected">
                <i class="fab fa-telegram"></i>
                <p>选择一个对话开始聊天</p>
            </div>
        </div>

        <div class="chat-input">
            <input type="text" id="message-input" placeholder="输入消息..." disabled>
            <button class="send-button" id="send-button" disabled>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="white">
                    <path d="M2 21l21-9L2 3v7l15 2-15 2v7z" />
                </svg>
            </button>
        </div>
    </div>

    <script>
        // 初始数据
        const initialData = {
            dialogs: [
                {
                    id: 1,
                    name: "Alice",
                    avatar: "A",
                    lastMessage: "你好！最近怎么样？",
                    lastMessageTime: "14:20",
                    unreadCount: 0
                },
                {
                    id: 2,
                    name: "Bob",
                    avatar: "B",
                    lastMessage: "明天一起吃饭吗？",
                    lastMessageTime: "昨天",
                    unreadCount: 3
                },
                {
                    id: 3,
                    name: "Charlie",
                    avatar: "C",
                    lastMessage: "我发送给你那份文件了吗？",
                    lastMessageTime: "周三",
                    unreadCount: 0
                },
                {
                    id: 4,
                    name: "Diana",
                    avatar: "D",
                    lastMessage: "谢谢你的帮助！",
                    lastMessageTime: "周一",
                    unreadCount: 1
                },
                {
                    id: 5,
                    name: "Telegram Group",
                    avatar: "T",
                    lastMessage: "欢迎新成员！",
                    lastMessageTime: "11:30",
                    unreadCount: 12
                }
            ],
            messages: {
                1: [
                    { id: 1, sender: "incoming", content: "你好！最近怎么样？", time: "14:20" },
                    { id: 2, sender: "outgoing", content: "我很好，谢谢关心！工作有点忙，但还不错。", time: "14:22" },
                    { id: 3, sender: "incoming", content: "那太好了！周末有什么计划吗？", time: "14:23" },
                    { id: 4, sender: "outgoing", content: "我打算去爬山，你想一起来吗？", time: "14:25" }
                ],
                2: [
                    { id: 1, sender: "incoming", content: "嗨，在忙吗？", time: "10:15" },
                    { id: 2, sender: "outgoing", content: "不太忙，怎么了？", time: "10:20" },
                    { id: 3, sender: "incoming", content: "明天一起吃饭吗？", time: "10:22" }
                ],
                3: [
                    { id: 1, sender: "outgoing", content: "你好Charlie，项目进展如何？", time: "09:30" },
                    { id: 2, sender: "incoming", content: "很顺利！我发送给你那份文件了吗？", time: "09:35" }
                ],
                4: [
                    { id: 1, sender: "incoming", content: "非常感谢你昨天的帮助！", time: "08:45" },
                    { id: 2, sender: "outgoing", content: "不客气，随时乐意帮忙！", time: "08:50" },
                    { id: 3, sender: "incoming", content: "谢谢你的帮助！", time: "08:52" }
                ],
                5: [
                    { id: 1, sender: "incoming", content: "大家好！", time: "11:20" },
                    { id: 2, sender: "incoming", content: "欢迎新成员！", time: "11:25" },
                    { id: 3, sender: "outgoing", content: "谢谢，很高兴加入！", time: "11:28" }
                ]
            }
        };

        // 应用状态
        let state = {
            currentDialogId: null,
            dialogs: [],
            messages: {}
        };

        // DOM 元素
        const dialogsList = document.getElementById('dialogs-list');
        const chatMessages = document.getElementById('chat-messages');
        const noChatSelected = document.getElementById('no-chat-selected');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const currentChatAvatar = document.getElementById('current-chat-avatar');
        const currentChatName = document.getElementById('current-chat-name');
        const searchInput = document.getElementById('search-input');
        const searchResults = document.getElementById('search-results');

        // 初始化应用
        function initApp() {
            loadData();
            renderDialogsList();
            setupEventListeners();
        }

        // 加载数据
        function loadData() {
            const savedData = localStorage.getItem('telegram-chat-data');

            if (savedData) {
                const parsedData = JSON.parse(savedData);
                state.dialogs = parsedData.dialogs;
                state.messages = parsedData.messages;
            } else {
                state.dialogs = initialData.dialogs;
                state.messages = initialData.messages;
                saveData();
            }
        }

        // 保存数据到localStorage
        function saveData() {
            localStorage.setItem('telegram-chat-data', JSON.stringify({
                dialogs: state.dialogs,
                messages: state.messages
            }));
        }

        // 渲染对话列表
        function renderDialogsList() {
            dialogsList.innerHTML = '';

            state.dialogs.forEach(dialog => {
                const dialogElement = document.createElement('div');
                dialogElement.className = `dialog-item ${state.currentDialogId === dialog.id ? 'active' : ''}`;
                dialogElement.dataset.id = dialog.id;

                dialogElement.innerHTML = `
                    <div class="dialog-avatar">${dialog.avatar}</div>
                    <div class="dialog-info">
                        <div class="dialog-name">
                            <span>${dialog.name}</span>
                            <span class="dialog-time">${dialog.lastMessageTime}</span>
                        </div>
                        <div class="dialog-last-message">${dialog.lastMessage}</div>
                    </div>
                    ${dialog.unreadCount > 0 ? `<div class="unread-count">${dialog.unreadCount}</div>` : ''}
                `;

                dialogsList.appendChild(dialogElement);
            });
        }

        // 渲染聊天消息
        function renderChatMessages(dialogId) {
            chatMessages.innerHTML = '';

            if (!dialogId) {
                noChatSelected.style.display = 'flex';
                return;
            }

            noChatSelected.style.display = 'none';

            const messages = state.messages[dialogId] || [];

            messages.forEach(message => {
                const messageElement = document.createElement('div');
                messageElement.className = `message message-${message.sender}`;

                messageElement.innerHTML = `
                    <div class="message-content">${message.content}</div>
                    <div class="message-time-${message.sender}">${message.time}</div>
                `;

                chatMessages.appendChild(messageElement);
            });

            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;

            // 更新当前对话信息
            const dialog = state.dialogs.find(d => d.id === dialogId);
            if (dialog) {
                currentChatAvatar.textContent = dialog.avatar;
                currentChatName.textContent = dialog.name;
            }
        }

        // 发送消息
        function sendMessage() {
            const content = messageInput.value.trim();
            if (!content || !state.currentDialogId) return;

            // 创建新消息
            const newMessage = {
                id: Date.now(),
                sender: "outgoing",
                content: content,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            };

            // 添加到消息列表
            if (!state.messages[state.currentDialogId]) {
                state.messages[state.currentDialogId] = [];
            }
            state.messages[state.currentDialogId].push(newMessage);

            // 更新对话的最后消息
            const dialogIndex = state.dialogs.findIndex(d => d.id === state.currentDialogId);
            if (dialogIndex !== -1) {
                state.dialogs[dialogIndex].lastMessage = content;
                state.dialogs[dialogIndex].lastMessageTime = "刚刚";
            }

            // 保存并更新UI
            saveData();
            renderChatMessages(state.currentDialogId);
            renderDialogsList();

            // 清空输入框
            messageInput.value = '';

            // 模拟回复
            setTimeout(() => {
                simulateReply();
            }, 1000);
        }

        // 模拟回复
        function simulateReply() {
            const replies = [
                "好的，收到你的消息了！",
                "很有趣的想法！",
                "让我考虑一下...",
                "谢谢分享！",
                "我同意你的观点",
                "稍后我们再详细讨论"
            ];

            const randomReply = replies[Math.floor(Math.random() * replies.length)];

            const replyMessage = {
                id: Date.now(),
                sender: "incoming",
                content: randomReply,
                time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            };

            state.messages[state.currentDialogId].push(replyMessage);

            // 更新对话的最后消息
            const dialogIndex = state.dialogs.findIndex(d => d.id === state.currentDialogId);
            if (dialogIndex !== -1) {
                state.dialogs[dialogIndex].lastMessage = randomReply;
                state.dialogs[dialogIndex].lastMessageTime = "刚刚";
            }

            saveData();
            renderChatMessages(state.currentDialogId);
            renderDialogsList();
        }

        // 搜索功能
        function performSearch(query) {
            if (!query) {
                searchResults.style.display = 'none';
                return;
            }

            const results = [];
            const lowerQuery = query.toLowerCase();

            // 搜索对话
            state.dialogs.forEach(dialog => {
                if (dialog.name.toLowerCase().includes(lowerQuery)) {
                    results.push({
                        type: 'dialog',
                        id: dialog.id,
                        name: dialog.name,
                        avatar: dialog.avatar,
                        text: `对话: ${dialog.name}`
                    });
                }
            });

            // 搜索消息
            for (const dialogId in state.messages) {
                const dialog = state.dialogs.find(d => d.id === parseInt(dialogId));
                if (dialog) {
                    state.messages[dialogId].forEach(message => {
                        if (message.content.toLowerCase().includes(lowerQuery)) {
                            results.push({
                                type: 'message',
                                id: dialogId,
                                name: dialog.name,
                                avatar: dialog.avatar,
                                text: `消息: ${message.content.substring(0, 30)}...`
                            });
                        }
                    });
                }
            }

            // 显示搜索结果
            displaySearchResults(results);
        }

        // 显示搜索结果
        function displaySearchResults(results) {
            searchResults.innerHTML = '';

            if (results.length === 0) {
                searchResults.innerHTML = '<div class="empty-state">没有找到匹配的结果</div>';
            } else {
                results.forEach(result => {
                    const resultElement = document.createElement('div');
                    resultElement.className = 'search-result-item';
                    resultElement.innerHTML = `
                        <i class="fas ${result.type === 'dialog' ? 'fa-user' : 'fa-comment'}"></i>
                        <div class="dialog-avatar">${result.avatar}</div>
                        <div class="result-info">
                            <div class="result-name">${result.name}</div>
                            <div class="result-text">${result.text}</div>
                        </div>
                    `;

                    resultElement.addEventListener('click', () => {
                        switchToDialog(parseInt(result.id));
                        searchResults.style.display = 'none';
                        searchInput.value = '';
                    });

                    searchResults.appendChild(resultElement);
                });
            }

            searchResults.style.display = 'block';
        }

        // 切换到指定对话
        function switchToDialog(dialogId) {
            state.currentDialogId = dialogId;
            messageInput.disabled = false;
            sendButton.disabled = false;
            renderDialogsList();
            renderChatMessages(dialogId);
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 对话项点击事件
            dialogsList.addEventListener('click', (e) => {
                const dialogItem = e.target.closest('.dialog-item');
                if (dialogItem) {
                    const dialogId = parseInt(dialogItem.dataset.id);
                    switchToDialog(dialogId);
                }
            });

            // 发送按钮点击事件
            sendButton.addEventListener('click', sendMessage);

            // 输入框回车事件
            messageInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });

            // 搜索功能
            searchInput.addEventListener('input', (e) => {
                performSearch(e.target.value);
            });

            // 点击页面其他区域关闭搜索结果
            document.addEventListener('click', (e) => {
                if (!e.target.closest('.search-container')) {
                    searchResults.style.display = 'none';
                }
            });
        }

        // 初始化应用
        window.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>

</html>